<script>
	export default {
		onLaunch: function() {
			if(!uni.getStorageSync('token')){
				this.getCode();
			}
			if(!uni.getStorageSync('user')){
				this.getAuthorize();
			}
			
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods:{
			getCode(){
				let self = this;
				//#ifdef MP-WEIXIN
				uni.login({
					success(res){
						console.log(res)
						self.onLogin(res)
					}
				})
				//#endif
			},
			async onLogin(message){
				const res = await this.$http.post(`/wechatmini/user/login`,{
					code:message.code
				});
				uni.setStorageSync('token',res.data.api_token)
				uni.setStorageSync('openid',res.data.openid)
			},
			getAuthorize(){
				let self = this;
				//#ifdef MP-WEIXIN
				uni.showModal({
					title: '温馨提示',
					content: '亲，授权微信登录后才能正常使用小程序功能',
					showCancel:false,
					complete(res) {
						if(res.confirm){
							self.getUserInfo()
						}
					}
				  })
				  //#endif
			},
			getUserInfo(){
				uni.getUserProfile({
					desc:"用于登录用户信息展示",
					success(res){
						uni.setStorageSync('user',res.userInfo)
					},
					fail(){
						uni.setStorageSync('user',{
							avatarUrl:'http://qiniu.disciplineeducation.com/studyIcons/timg.jpg',
							nickName:'微信用户',
							isLogin:false
						})
					}
				})
			}
		}
	}
</script>
<style lang="scss">
	page{
		height:100%;
		font-size:28rpx;
		background-color: #f0f0f0;
	}
	/*每个页面公共css */
    @import "uview-ui/index.scss";
</style>
 